<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Devious Baton Protocol Example</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 800px;
      margin: 0 auto;
      padding: 20px;
    }
    h1 {
      text-align: center;
    }
    .form-group {
      margin-bottom: 15px;
    }
    label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
    }
    input[type="text"], input[type="number"] {
      width: 100%;
      padding: 8px;
      box-sizing: border-box;
    }
    button {
      padding: 10px 15px;
      background-color: #4285f4;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
    button:hover {
      background-color: #3367d6;
    }
    #log {
      margin-top: 20px;
      padding: 10px;
      border: 1px solid #ccc;
      height: 300px;
      overflow-y: auto;
      background-color: #f9f9f9;
      font-family: monospace;
    }
    .info { color: #0077cc; }
    .success { color: #00cc00; }
    .error { color: #cc0000; }
  </style>
</head>
<body>
  <h1>Devious Baton Protocol Demo</h1>

  <div class="form-group">
    <label for="serverUrl">WebTransport Server URL:</label>
    <input type="text" id="serverUrl" value="https://localhost:8443/webtransport/devious-baton" />
  </div>

  <div class="form-group">
    <label for="version">Protocol Version:</label>
    <input type="number" id="version" value="0" min="0" />
  </div>

  <div class="form-group">
    <label for="baton">Initial Baton Value (1-255, leave empty for random):</label>
    <input type="number" id="baton" min="1" max="255" />
  </div>

  <div class="form-group">
    <label for="count">Number of Batons:</label>
    <input type="number" id="count" value="1" min="1" max="10" />
  </div>

  <button id="connectButton">Connect</button>
  <button id="disconnectButton" disabled>Disconnect</button>

  <div id="log"></div>

  <!-- Include the Devious Baton Client Library -->
  <script src="devious_baton_client.js"></script>

  <script>
    // DOM elements
    const serverUrlInput = document.getElementById('serverUrl');
    const versionInput = document.getElementById('version');
    const batonInput = document.getElementById('baton');
    const countInput = document.getElementById('count');
    const connectButton = document.getElementById('connectButton');
    const disconnectButton = document.getElementById('disconnectButton');
    const logElement = document.getElementById('log');

    // Client instance
    let client = null;

    // Log function
    function log(message, type = 'info') {
      const now = new Date().toLocaleTimeString();
      const entry = document.createElement('div');
      entry.className = type;
      entry.textContent = `[${now}] ${message}`;
      logElement.appendChild(entry);
      logElement.scrollTop = logElement.scrollHeight;
    }

    // Connect button click handler
    connectButton.addEventListener('click', async () => {
      try {
        // Get values from form
        const serverUrl = serverUrlInput.value;
        const version = parseInt(versionInput.value, 10);
        const count = parseInt(countInput.value, 10);
        let baton = batonInput.value ? parseInt(batonInput.value, 10) : null;

        // Validate inputs
        if (!serverUrl) {
          log('Server URL is required', 'error');
          return;
        }

        if (isNaN(version) || version < 0) {
          log('Version must be a non-negative number', 'error');
          return;
        }

        if (baton !== null && (isNaN(baton) || baton < 1 || baton > 255)) {
          log('Baton value must be between 1 and 255', 'error');
          return;
        }

        if (isNaN(count) || count < 1) {
          log('Count must be a positive number', 'error');
          return;
        }

        // Create client options
        const options = {
          version,
          count
        };

        if (baton !== null) {
          options.baton = baton;
        }

        log(`Connecting to ${serverUrl} with options: ${JSON.stringify(options)}`, 'info');

        // Create and connect client
        client = new DeviousBatonClient(serverUrl, options);

        // Set up callbacks
        client.onConnected = () => {
          log('Connected to server', 'success');
          connectButton.disabled = true;
          disconnectButton.disabled = false;
        };

        client.onBatonReceived = (value, streamType) => {
          log(`Received baton ${value} on ${streamType} stream`, 'info');
        };

        client.onBatonSent = (value, streamType) => {
          log(`Sent baton ${value} on ${streamType} stream`, 'info');
        };

        client.onDatagramReceived = (value) => {
          log(`Received datagram with baton ${value}`, 'info');
        };

        client.onDatagramSent = (value) => {
          log(`Sent datagram with baton ${value}`, 'info');
        };

        client.onComplete = () => {
          log('Protocol complete!', 'success');
          connectButton.disabled = false;
          disconnectButton.disabled = true;
        };

        client.onError = (error) => {
          log(`Error: ${error.message}`, 'error');
        };

        // Connect to server
        const connected = await client.connect();
        if (!connected) {
          log('Failed to connect', 'error');
        }
      } catch (error) {
        log(`Error: ${error.message}`, 'error');
      }
    });

    // Disconnect button click handler
    disconnectButton.addEventListener('click', async () => {
      if (client) {
        try {
          await client.close();
          log('Disconnected from server', 'info');
          connectButton.disabled = false;
          disconnectButton.disabled = true;
        } catch (error) {
          log(`Error disconnecting: ${error.message}`, 'error');
        }
      }
    });

    // Display WebTransport availability
    if (typeof WebTransport === 'undefined') {
      log('WebTransport is not available in your browser. Please use a browser that supports WebTransport (like Chrome 97+).', 'error');
    } else {
      log('WebTransport is available in your browser!', 'success');
    }
  </script>
</body>
</html>
